package com.teach.sys.api;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teach.sys.dto.UserRegDto;
import com.teach.sys.entity.User;
import com.teach.sys.service.UserService;

import cn.hutool.core.util.StrUtil;


 /**
 * <pre>
 * - 系统用户前端API控制器
 * Author : J.L.Zhou
 * E-Mail : 12020042
 * Tel : 151 1104 7708
 * Date : 2022-10-24 23:41
 * Version : 1.0
 * Copyright 2021 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 */
@RestController
@RequestMapping("/sys/user")
public class UserApi {

	@Autowired
	private UserService userService;



	@GetMapping("list")
	public Object list() throws Exception {
		return userService.list();
	}

	@GetMapping("page")
	public Object page(Page<User> page,String roleId,String key) throws Exception {
		LambdaQueryWrapper<User> q = new LambdaQueryWrapper<>();//条件构造器
		// and role_id=#{roleId}
		q.eq(StrUtil.isNotBlank(roleId), User::getRoleId, roleId)
		// and (user_name like '%${key}%' or user_tel like '%${key}%')
		.and(StrUtil.isNotBlank(key), q1->q1.like(User::getUserName, key).or().like(User::getUserTel, key))
		// order by user_id desc;
		.orderByDesc(User::getUserId);
		
		return userService.page(page,q);
	}

	@GetMapping("{id}")
	public Object id(@PathVariable("id") Integer userId) {
		return userService.getById(userId);
	}

	// @PostMapping
	// public void add(@RequestBody User user) {
	// 		userService.save(user);
	// }

	@PostMapping("reg")
	public User reg(@RequestBody @Validated UserRegDto user) {
		return userService.reg(user);
	}

	@PutMapping
	public void update(@RequestBody User user) {
		userService.updateById(user);
	}

	@PutMapping("reset-pwd")
	public void resetPwd(@RequestBody User user) {
		userService.resetPwd(user.getUserId(),user.getUserPwd());
	}

	@DeleteMapping("{id}")
	public void delete(@PathVariable("id") Integer userId) {
		userService.removeById(userId);
	}

	@DeleteMapping("ids")
	public void delete(Integer[] userId) {
		userService.removeByIds(Arrays.asList(userId));
	}

}
